<script lang="tsx" setup>
import { ContentWrap } from '@/components/ContentWrap'
import { Search } from '@/components/Search'
import { useI18n } from '@/hooks/web/useI18n'
import { ElButton } from 'element-plus'
import { Table } from '@/components/Table'
import { getListApi, delApi } from '@/api/lowcode'
import { useTable } from '@/hooks/web/useTable'
import { PropType, h, reactive, ref, unref } from 'vue'
import { CrudSchema, useCrudSchemas } from '@/hooks/web/useCrudSchemas'
import { useRoute, useRouter } from 'vue-router'
import { PageDataProperty } from '@/components/Lowcode/src/types/Lowcode'
import { useEmitt } from '@/hooks/event/useEmitt'
import { ElTag, ElInput } from 'element-plus'

const props = defineProps({
  pageConfig: {
    type: Object as PropType<PageDataProperty>,
    required: true
  }
})
const { push } = useRouter()

const route = useRoute()
const identifier = route.params.identifier

const ids = ref<string[]>([])

const searchParams = ref({})
const setSearchParams = (params: any) => {
  searchParams.value = params
  getList()
}

const { tableRegister, tableState, tableMethods } = useTable({
  fetchDataApi: async () => {
    const { currentPage, pageSize } = tableState
    const res = await getListApi(props.pageConfig.getListApi, {
      pageIndex: unref(currentPage),
      pageSize: unref(pageSize),
      ...unref(searchParams)
    })
    return {
      list: res.data.list,
      total: res.data.total
    }
  },
  fetchDelApi: async () => {
    const res = await delApi(props.pageConfig.delApi, unref(ids))
    return !!res
  }
})
const { loading, dataList, total, currentPage, pageSize } = tableState
const { getList, getElTableExpose, delList } = tableMethods

getList()

useEmitt({
  name: 'getList',
  callback: (type: string) => {
    if (type === 'add') {
      currentPage.value = 1
    }
    getList()
  }
})

const { t } = useI18n()

const crudSchemas = reactive<CrudSchema[]>(props.pageConfig.schemas)

const customFunction = (data: any, funcStr: string) => {
  const Fn = new Function('VUECustom', funcStr)
  let VUECustom = { h, ElTag, ElInput, data: data }
  return Fn(VUECustom)
}
crudSchemas.forEach((column: CrudSchema) => {
  if (column.table?.slots) {
    for (let slotName in column.table?.slots) {
      let funcStr = column.table?.slots[slotName]
      if (!funcStr) {
        delete column.table.slots[slotName]
        continue
      }
      column.table.slots[slotName] = (data) => {
        try {
          return customFunction(data, funcStr)
        } catch (e: any) {
          console.error(e.message)
          return data.row[column.field]
        }
      }
    }
  }
})

const { allSchemas } = useCrudSchemas(crudSchemas)

const AddAction = () => {
  push(`/lowcode/example-page/${identifier}/add`)
}

const delLoading = ref(false)

const delData = async (row: any) => {
  const elTableExpose = await getElTableExpose()
  ids.value = row ? [row.id] : elTableExpose?.getSelectionRows().map((v: any) => v.id) || []
  delLoading.value = true
  await delList(unref(ids).length).finally(() => {
    delLoading.value = false
  })
}

const action = (row: any, type: string) => {
  push(`/lowcode/example-page/${identifier}/${type}/${row.id}`)
}
</script>

<template>
  <ContentWrap>
    <!-- <h3>{{ pageConfig.title }}</h3> -->
    <h5>{{ pageConfig.caption }}</h5>
    <Search :isCol="true" :schema="allSchemas.searchSchema" @search="setSearchParams" @reset="setSearchParams" />
    <div class="mb-10px">
      <ElButton type="primary" @click="AddAction">{{ t('exampleDemo.add') }}</ElButton>
      <ElButton :loading="delLoading" type="danger" @click="delData(null)">
        {{ t('exampleDemo.del') }}
      </ElButton>
    </div>

    <Table
      v-model:pageSize="pageSize"
      v-model:currentPage="currentPage"
      :columns="allSchemas.tableColumns"
      :data="dataList"
      :loading="loading"
      :pagination="{
        total: total
      }"
      @register="tableRegister"
    >
      <template #action="{ row }">
        <ElButton type="primary" @click="action(row, 'edit')">
          {{ t('exampleDemo.edit') }}
        </ElButton>
        <ElButton type="success" @click="action(row, 'detail')">
          {{ t('exampleDemo.detail') }}
        </ElButton>
        <ElButton type="danger" @click="delData(row)">
          {{ t('exampleDemo.del') }}
        </ElButton>
      </template>
    </Table>
  </ContentWrap>
</template>
